package cn.snsprj.authclient.controller;

import cn.snsprj.authclient.common.SessionManage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author SKH
 * @date 2018-08-21 10:45
 **/
@Controller
public class UserController {

    @RequestMapping(value = "/user/info",method = {RequestMethod.GET})
    public String userInfoView(HttpServletRequest request){

        // 受保护的资源
        HttpSession session = request.getSession(true);
        session.setAttribute("s","s");

        return "userInfo";
    }

    @RequestMapping(value = "/index",method = {RequestMethod.GET})
    public String indexView(HttpServletRequest request){

        HttpSession session = request.getSession(false);
        if (session != null){
            return "redirect:/user/info";
        }
        return "index";
    }

    /**
     * logout，注意高可用集群
     * @param request
     */
    @RequestMapping(value = {"/logout", "/notified_logout"},method = {RequestMethod.GET})
    @ResponseBody
    public void logout(HttpServletRequest request){

        String serviceTicket = request.getParameter("serviceTicket");

        HttpSession session;
        if (StringUtils.isNotBlank(serviceTicket)){
            session = SessionManage.MANAGED_SESSIONS.get(serviceTicket);
            SessionManage.MANAGED_SESSIONS.remove(serviceTicket);
        }else {
            session = request.getSession(false);
        }

        if (session != null){
            session.invalidate();
        }
    }
}
